package com.liwentao.seckill.service.impl;

import com.liwentao.seckill.entity.User;
import com.liwentao.seckill.entity.vo.LoginVo;
import com.liwentao.seckill.exception.GlobalException;
import com.liwentao.seckill.mapper.UserMapper;
import com.liwentao.seckill.result.R;
import com.liwentao.seckill.result.ResponseEnum;
import com.liwentao.seckill.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liwentao.seckill.util.CookieUtil;
import com.liwentao.seckill.util.MD5Util;
import com.liwentao.seckill.util.RedisUtil;
import com.liwentao.seckill.util.UUIDUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2022-01-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    UserMapper userMapper;
    @Resource
    RedisTemplate redisTemplate;
    @Override
    public R login(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response){
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();
        //校验手机号和密码是否为空
//        if (null==mobile||null==password){
//            return R.error(ResponseEnum.LOGIN_REEOR);
//        }
        //校验手机号格式
//        if(!ValidatorUtil.isMobile(mobile)){
//            return R.error(ResponseEnum.MOBILE_REEOR);
//        }
        //查询
        User user = userMapper.selectById(mobile);
        if (null==user){
            throw new GlobalException(ResponseEnum.LOGIN_ERROR);
        }
        if(!MD5Util.fromPassToDBPass(password, user.getSalt()).equals(user.getPassword())){
            throw new GlobalException(ResponseEnum.LOGIN_ERROR);
        }
        String ticket= UUIDUtil.getUUID();
        redisTemplate.opsForValue().set("user:"+ticket, user);
        //存入session
//        request.getSession().setAttribute(ticket, user);
        CookieUtil.setCookie(request, response,"userTicket", ticket);
        System.out.println(ticket);
        return R.ok();
    }

    @Override
    public User getUserByCookie(String userTicket,HttpServletResponse response,HttpServletRequest request) {
        if(null==userTicket){
            return null;
        }
        User user = (User)redisTemplate.opsForValue().get("user:"+userTicket);
        System.out.println("getUserByCookie:"+user);
//        if(user!=null){
//            CookieUtil.setCookie(request,response,"user:"+userTicket,userTicket);
//        }
        return user;
    }
}
